<template>
  <el-select v-model="model" :placeholder="placeholder" clearable>
    <el-option v-for="opt in opts" :key="opt.dictValue" :label="opt.dictTitle" :value="opt.dictValue"/>
  </el-select>
</template>
<script setup>
import {computed, defineProps, ref, shallowRef, watchEffect} from 'vue';
import {DefaultFieldDefinition} from '@/components/form/DefaultFormDefinition';
import {handleLikeParam, isEmpty, real} from '@/utils/CommonUtils';
import {getAction} from '@/request/BaseRequest';

const props = defineProps({
  field: {
    type: Object,
    default() {
      return DefaultFieldDefinition;
    }
  }
});
const model = ref();
const opts = shallowRef([]);

function resetField() {
  model.value = undefined;
}

function getSearchFieldValue(searchData) {
  if (isEmpty(model.value)) return;
  searchData.eq.push({
    fieldName: props.field.tableFieldName,
    value: model.value
  });
}

const placeholder = computed(() => {
  if (isEmpty(props.field.id)) return '';
  return `请选择${props.field.alias ? props.field.alias : props.field.showName}`;
});

watchEffect(() => {
  if (isEmpty(props.field) || isEmpty(real(props.field))) {
    return;
  }

  let dictCode = real(props.field);
  loadDictOptions();
});

function loadDictOptions() {
  getAction('/plat/platDict/loadDictByCode',
    {dictCode: props.field.dictCode}).then(data => {
    if (data.success) {
      let result = data.result;
      opts.value = result.items;
    }
  });
}


defineExpose({
  getSearchFieldValue,
  resetField
});
</script>
